package model

import (
	"encoding/json"
	"github.com/gorilla/websocket"
	"io"
	"log"
	"net/http"
	"sort"
	"strconv"
	"strings"
	"sync"
	"text/template"
)

var (
	wg       sync.RWMutex
	wbsCon   *websocket.Conn
	upgrader = websocket.Upgrader{
		// 读取存储空间大小
		ReadBufferSize: 1024,
		// 写入存储空间大小
		WriteBufferSize: 1024,
		// 允许跨域
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
)

//http网页服务
func HttpServer() {
	http.Handle("/asset/", http.StripPrefix("/asset/", http.FileServer(http.Dir("asset"))))
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		tmpl := template.Must(template.ParseFiles("index.html"))
		mp := make(map[string]string)
		mp["HttpPort"] = HttpPort
		mp["UdpPort"] = UdpPort
		mp["Ip"] = GetIntranetIp()
		if err := tmpl.Execute(w, mp); err != nil {
			Log.Println("MapToJson err: ", err)
			log.Fatal(err)
		}
	})

	http.HandleFunc("/testSpeed", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Access-Control-Allow-Origin", "*")             //允许访问所有域
		w.Header().Add("Access-Control-Allow-Headers", "Content-Type") //header的类型
		w.Header().Set("content-type", "application/text")
		showspeed := showspeed()
		if _, err := io.WriteString(w, showspeed); err != nil {
			Log.Println("AJAX testSpeed WriteString err: ", err)
		}
		return
	})

	http.HandleFunc("/testPort", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Access-Control-Allow-Origin", "*")             //允许访问所有域
		w.Header().Add("Access-Control-Allow-Headers", "Content-Type") //header的类型
		w.Header().Set("content-type", "application/json")
		r.ParseForm()
		if res, err := TestPort(r.Form.Get("ip"), r.Form.Get("ports")); err != nil {
			Log.Println("AJAX testPort err: ", err)
		} else {
			resByte, _ := json.Marshal(res)
			if _, err := io.WriteString(w, string(resByte)); err != nil {
				Log.Println("AJAX testPort WriteString err: ", err)
			}
		}
		return
	})

	http.HandleFunc("/LogClean", func(w http.ResponseWriter, r *http.Request) {
		MacInfo := MacInfo{TYPE: 1}
		JsonMacInfo, _ := json.Marshal(MacInfo)
		if _, err := client.Write(JsonMacInfo); err != nil {
			Log.Println("client.Write Err:", err.Error())
			panic(err)
		}
		return
	})

	http.HandleFunc("/echarts", func(w http.ResponseWriter, r *http.Request) {
		/**
		{
			"192.168.111.134": { 离线IP
				"10.0.16.58": { 本机IP1
					"time": "2019/06/20 09:39:09|2019/06/20 09:41:24|"
				}
			},
			"192.168.111.135": {
				"10.0.16.58": { 本机IP2
					"time": "2019/06/20 09:39:09|"
				}
			},
			"192.168.111.136": {
				"10.0.16.58": { 本机IP3
					"time": "2019/06/20 09:39:09|"
				}
			}
		}

		*/

		type times struct {
			Name  string `json:"name"`
			Value string `json:"value"`
		}

		type selfIp struct {
			Name     string  `json:"name"`
			Children []times `json:"children"`
		}

		type remoteIp struct {
			Name     string   `json:"name"`
			Children []selfIp `json:"children"`
		}

		type echarts struct {
			Name     string     `json:"name"`
			Children []remoteIp `json:"children"`
		}

		var keys []string
		for k := range OffOlineMac {
			keys = append(keys, k)
		}
		sort.Strings(keys)

		var _echarts echarts
		_echarts.Name = "离线统计图"
		var _remoteIps []remoteIp
		var _remoteIp remoteIp
		var _times []times
		var _time times
		var _selfIps []selfIp
		var _selfIp selfIp
		times_list := []string{}
		for _, k1 := range keys { //远程ip
			v1 := OffOlineMac[k1]
			_selfIps = []selfIp{}
			for k2, v2 := range v1 { //本机ip
				for _, v3 := range v2 { //时间
					times_list = strings.Split(v3[:len(v3)-1], "|")
					_times = []times{}
					for _, v4 := range times_list {
						_time.Name = "离线时间[" + v4 + "]"
						_time.Value = ""
						_times = append(_times, _time)
					}
				}

				_selfIp.Name = "检测设备【" + k2 + "】[" + strconv.Itoa(len(times_list)) + " 个记录]"
				times_list = []string{}
				_selfIp.Children = _times
				_selfIps = append(_selfIps, _selfIp)
			}

			_remoteIp.Name = "离线设备【" + k1 + "】"
			_remoteIp.Children = _selfIps
			_selfIps = []selfIp{}
			_remoteIps = append(_remoteIps, _remoteIp)

		}
		_echarts.Children = _remoteIps
		resByte, _ := json.Marshal(_echarts)
		if _, err := io.WriteString(w, string(resByte)); err != nil {
			Log.Println("AJAX testPort WriteString err: ", err)
		}
		return
	})

	http.HandleFunc("/setMac", func(w http.ResponseWriter, r *http.Request) {
		r.ParseForm()
		_ip := r.Form.Get("ip")
		_type := r.Form.Get("type")
		_info := r.Form.Get("info")
		if _ip != "" && _type != "" && _info != "" {
			wg.Lock()
			if _, ok := Mac[_ip]; ok {
				Mac[_ip][_type] = _info
				Mac[_ip][_type] = _info
			}
			wg.Unlock()
		}
		return
	})

	http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
		var err error
		// 完成http应答，在httpheader中放下如下参数
		if wbsCon, err = upgrader.Upgrade(w, r, nil); err != nil {
			return // 获取连接失败直接返回
		}

		/**
		for {
			// 只能发送Text, Binary 类型的数据,下划线意思是忽略这个变量.
			if _, data, err := wbsCon2.ReadMessage();err == nil {
				dataStr := string(data)
				if dataStr == "testSpeed"{
					showspeed := showspeed()
					if err = wbsCon2.WriteMessage(websocket.TextMessage, []byte(showspeed)); err != nil {
						wbsCon2.Close()
					}
				}
			}else{
				wbsCon2.Close()
			}
		}
		**/
	})

	err := http.ListenAndServe(":"+HttpPort, nil)
	if err != nil {
		Log.Println("MapToJson err: ", err)
		log.Fatal(err)
	}
}
